import 'package:flutter/material.dart';
import 'package:provide/provide.dart';
import 'package:flutter_shop/provide/cart.dart';
import 'package:flutter_shop/model/cartInfo.dart';
import 'cart_page/cart_item.dart';
import 'package:flutter_shop/pages/cart_page/cart_bottom.dart';

class CartPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('购物车'),
      ),
      body: FutureBuilder(
        future: _getCartInfo(context),
        builder: (context, snapshot) {
          //有数据则处理
          if (snapshot.hasData) {
            //获取cartList购物车列表
            List<CartInfoModel> cartList;
            return Provide<CartProvide>(builder: (context, child, cartInfo) {
              cartList = cartInfo.cartList;
              return cartList.length==0?noCart():hasCart(cartList);
            });
          } else {
            //无数据则返回加载中
            return Text('正在加载中.....');
          }
        },
      ),
    );
  }

  /*
   * 当无商品时显示
   */
  Widget noCart() {
    return Center(
      child: Text('当前无选购商品，请到商城选购'),
    );
  }

  /*
  有商品时显示布局
   */
  Widget hasCart(List<CartInfoModel> cartList) {
    return Stack(
      children: <Widget>[
        ListView.builder(
          itemCount: cartList.length,
          itemBuilder: (context, index) {
            return CartItem(cartItem: cartList[index]);
          },
        ),
        Positioned(
          bottom: 0.0,
          left: 0.0,
          child: CartBottom(),
        ),
      ],
    );
  }

  Future<String> _getCartInfo(BuildContext context) async {
    await Provide.value<CartProvide>(context).getCartInfo();
    return 'end';
  }
}
